package zoolisten;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Player {
    public static void main(String[] args) {
        try {
            ZooKeeper zooKeeper = new ZooKeeper(
                    "master:2181", 3600,
                    new DWatcher());

            String filename = "/home/xieweig/document/mm.txt";
            Path path = Paths.get(filename);
            if (!Files.exists(path)) Files.createFile(path);
            assert args[0] != null;
            new Thread(new PlayerRunner(zooKeeper, filename, args[0])).start();
            System.out.println("player主线程完成初始化堆内存变量的任务就可以死了");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class PlayerRunner implements Runnable {

    private Stat someStat;
    private ZooKeeper zooKeeper;
    //
//    private CountDownLatch countDownLatch;
    private ReentrantLock reentrantLock;
    private Condition tag;

    private ReentrantLock sick;
    private Condition sickTag;
    private String t;
    private Path file;


    public PlayerRunner(ZooKeeper zooKeeper, String filename, String arg) {
        t = arg;
//        this.countDownLatch = new CountDownLatch(1);
        this.someStat = new Stat();
        this.zooKeeper = zooKeeper;
        this.reentrantLock = new ReentrantLock();
        this.tag = reentrantLock.newCondition();
        this.sick = new ReentrantLock();
        this.sickTag = sick.newCondition();

        this.file = Paths.get(filename);


    }

    @Override
    public void run() {
        while (true) {

            try {
                byte[] data = zooKeeper.getData("/some", event -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print("第二次回复结果 some :");
                    Trainer.debugEX(event);
//                    Trainer.debugEX(someStat);

//                    countDownLatch.countDown();
                    reentrantLock.lock();
                    try {
                        tag.signal();
                    } finally {
                        reentrantLock.unlock();
                    }

                }, someStat);
                Trainer.debugEX("第一次回复结果　some : " + new String(data));
                Trainer.debugEX(someStat);

            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            reentrantLock.lock();
            try {
                tag.await();
//                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
//            循环抢锁　知道抢到修改权限
            try {
                while (true) {

                    try {
                        zooKeeper.create("/writer", "init".getBytes(),
                                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                    } catch (KeeperException e) {
                        System.out.println("占座失败，只能积极期待下一次　" + e.code());
                        //期望
                        try {
                            byte[] data = zooKeeper.getData("/writer", (event -> {
                                Trainer.debugEX(event);
                                if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
                                    sick.lock();
                                    try {
                                        sickTag.signal();
                                    } finally {
                                        sick.unlock();
                                    }

                                }
                            }), null);
                            Trainer.debugEX(new String(data));
                            //等待
                            sick.lock();
                            try {
                                sickTag.await();
                            } catch (InterruptedException ee) {
                                ee.printStackTrace();
                            } finally {
                                sick.unlock();
                            }
                        } catch (KeeperException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                        continue;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    break;
                }


                System.out.println("占座成功，可以愉快的玩耍了");
                try {
                    Content content = new Content(file);
                    content.writeInto(t);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                try {
                    zooKeeper.delete("/writer", -1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (KeeperException e) {
                    e.printStackTrace();
                }
            }


        }


    }
}
